﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LevelDB
{
    public class ChunkHandle
    {
        public enum Situation
        {
            InDisk,
            InMemory,
            Both,
        }
        public long? fileOffset;
        public byte[,,] data;

        public bool active = false;

        public Situation situation
        {
            get
            {
                if (!fileOffset.HasValue) return Situation.InMemory;
                if (data != null) return Situation.Both;
                return Situation.InDisk;
            }
        }

        public bool Waiting => active && data == null;
        public bool Saving => !active && data != null;

        internal ChunkHandle(long fileOffset)
        {
            data = null;
            this.fileOffset = fileOffset;
        }

        internal ChunkHandle(byte[,,] data)
        {
            this.data = data;
            fileOffset = null;
        }
        public void SetData((int x, int y, int z) p, byte id)
        {
            if (p.x < 0 || p.x > data.GetLength(0)) return;
            if (p.y < 0 || p.y > data.GetLength(1)) return;
            if (p.z < 0 || p.z > data.GetLength(2)) return;

            data[p.x, p.y, p.z] = id;
        }

        public byte GetData(int x, int y, int z)
        {
            return data[x, y, z];
        }

        public ChunkHandle MakeRef()
        {
            active = true;
            return this;
        }

        public void ReleaseRef()
        {
            active = false;
        }
    }
}
